<template>
  <div ref="chartRef" style="width: 920px; height: 438px;"></div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref(null);

onMounted(() => {
  getChart();
})
const getChart = () => {
     const myChart = echarts.init(chartRef.value)
     const option = {
    tooltip: {
      trigger: 'item',
      axisPointer: {
        type: 'shadow'
      },
    },
    legend: {
      data: ['美云销', '工程', '电商下沉', 'KA&TOP'],
      top: 0,
      icon: 'rect',
      itemWidth: 12,
      itemHeight: 12,
      itemGap: 40,
      textStyle: {
        fontSize: 12,
        lineHeight: 12,
        color: '#4E5969',
      }
    },
    grid: {
      left: '3%',
      right: '10%',
      bottom: '8%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '达成规模',
      nameLocation: 'center',
      nameGap: 30,
      axisLabel: {
        formatter: '{value}'
      }
    },
    yAxis: {
      type: 'category',
      data: ['订单', '提货', '安装'],
      axisLine: {
        show: true
      },
      axisTick: {
        show: true
      }
    },
    series: [
      {
        name: '美云销',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          position: 'inside',
          color: '#1D2129',
          formatter: function (params) {
            return params.data.percent + '%';
          }
        },
        data:  [
          { value: 27.97, percent: 34 },
          { value: 23.93, percent: 28 },
          { value: 33.72, percent: 28 }
        ],
        itemStyle: {
          color: '#1088FF'
        }
      },
      {
        name: '工程',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          position: 'inside',
          color: '#1D2129',
          formatter: function (params) {
            return params.data.percent + '%';
          }
        },
        data: [
          { value: 27.97, percent: 39 },
          { value: 23.93, percent: 47 },
          { value: 33.72, percent: 47 }
        ],
        itemStyle: {
          color: '#29CF93'
        }
      },
      {
        name: '电商下沉',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          position: 'inside',
          color: '#1D2129',
          formatter: function (params) {
            return params.data.percent + '%';
          }
        },
        data: [
          { value: 27.97, percent: 16 },
          { value: 23.93, percent: 16 },
          { value: 33.72, percent: 16 }
        ],
        itemStyle: {
          color: '#859BBB'
        }
      },
      {
        name: 'KA&TOP',
        type: 'bar',
        stack: 'total',
        label: {
          show: true,
          position: 'inside',
          color: '#1D2129',
          formatter: function (params) {
            return params.data.percent + '%';
          }
        },
        data: [
          { value: 27.97, percent: 11 },
          { value: 23.93, percent: 11 },
          { value: 33.72, percent: 9 }
        ],
        itemStyle: {
          color: '#FFB928'
        }
      }
    ],
    graphic: [] // 初始为空，将在渲染后动态设置
  }
  myChart.setOption(option);

  // 监听渲染完成事件
  myChart.on('rendered', function() {
    try {
      // 获取图表实例
      const chartInstance = myChart;
      
      // 获取每个柱状图的长度和位置
      const barData = [];
      
      // 遍历每个系列
      option.series.forEach((series, seriesIndex) => {
        // 获取系列模型
        const seriesModel = chartInstance.getModel().getSeriesByIndex(seriesIndex);
        
        // 遍历每个数据点
        series.data.forEach((dataItem, dataIndex) => {
          // 获取数据点的图形元素
          const data = seriesModel.getData();
          const graphicEl = data.getItemGraphicEl(dataIndex);
          
          if (graphicEl && graphicEl.shape) {
            // 获取柱状图的形状信息
            const shape = graphicEl.shape;
            
            // 计算柱状图的右边界（x + width）
            const barRight = shape.x + shape.width;
            const barCenterY = shape.y + shape.height / 2;
            
            // 存储柱状图信息
            if (!barData[dataIndex]) {
              barData[dataIndex] = [];
            }
            barData[dataIndex][seriesIndex] = {
              right: barRight,
              centerY: barCenterY,
              value: dataItem.value
            };
          }
        });
      });
      
      // 找到每个类别（y轴）中最长的柱状图
      const maxBarRights = [];
      const barCenters = [];
      
      for (let i = 0; i < barData.length; i++) {
        if (barData[i]) {
          const rights = barData[i].map(bar => bar.right);
          maxBarRights[i] = Math.max(...rights);
          
          // 取第一个柱状图的中心位置作为类别的中心
          barCenters[i] = barData[i][0].centerY;
        }
      }
      
      // 动态设置 graphic 文本位置
      const graphicElements = [];
      
      // 为每个类别添加文本
      for (let i = 0; i < maxBarRights.length; i++) {
        if (maxBarRights[i] !== undefined) {
          // 金额文本
          graphicElements.push({
            type: 'text',
            left: maxBarRights[i] + 10,
            top: barCenters[i] - 6, // 调整垂直位置使其居中
            style: {
              text: i === 0 ? '27.97亿' : (i === 1 ? '23.93亿' : '33.72亿'),
              fill: '#1D2129',
              fontSize: 12
            }
          });
          
          // 百分比文本
          graphicElements.push({
            type: 'text',
            left: maxBarRights[i] + 50,
            top: barCenters[i] - 6,
            style: {
              text: i === 0 ? '▼ 15.1%' : (i === 1 ? '▼ 10.5%' : '▲ 4.4%'),
              fill: i === 2 ? '#91CC75' : '#EE6666',
              fontSize: 12
            }
          })
        }
      }
      
      // 更新图表配置
      myChart.setOption({
        graphic: graphicElements
      })
      
    } catch (error) {
      console.error('获取柱状图尺寸时出错:', error)
    }
  });

  window.addEventListener('resize', function () {
    myChart.resize()
  })
}
</script>